{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Contains a variant of the densenet model definition.\"\"\"\n",
    "\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "slim = tf.contrib.slim\n",
    "\n",
    "\n",
    "def trunc_normal(stddev): return tf.truncated_normal_initializer(stddev=stddev)\n",
    "\n",
    "\n",
    "def bn_act_conv_drp(current, num_outputs, kernel_size, scope='block'):\n",
    "    current = slim.batch_norm(current, scope=scope + '_bn')\n",
    "    current = tf.nn.relu(current)\n",
    "    current = slim.conv2d(current, num_outputs, kernel_size, scope=scope + '_conv')\n",
    "    current = slim.dropout(current, scope=scope + '_dropout')\n",
    "    return current\n",
    "\n",
    "\n",
    "def block(net, layers, growth, scope='block'):\n",
    "    for idx in range(layers):\n",
    "        bottleneck = bn_act_conv_drp(net, 4 * growth, [1, 1],\n",
    "                                     scope=scope + '_conv1x1' + str(idx))\n",
    "        tmp = bn_act_conv_drp(bottleneck, growth, [3, 3],\n",
    "                              scope=scope + '_conv3x3' + str(idx))\n",
    "        net = tf.concat(axis=3, values=[net, tmp])\n",
    "    return net\n",
    "\n",
    "\n",
    "def densenet(images, num_classes=1001, is_training=False,\n",
    "             dropout_keep_prob=0.8,\n",
    "             scope='densenet'):\n",
    "    \"\"\"Creates a variant of the densenet model.\n",
    "\n",
    "      images: A batch of `Tensors` of size [batch_size, height, width, channels].\n",
    "      num_classes: the number of classes in the dataset.\n",
    "      is_training: specifies whether or not we're currently training the model.\n",
    "        This variable will determine the behaviour of the dropout layer.\n",
    "      dropout_keep_prob: the percentage of activation values that are retained.\n",
    "      prediction_fn: a function to get predictions out of logits.\n",
    "      scope: Optional variable_scope.\n",
    "\n",
    "    Returns:\n",
    "      logits: the pre-softmax activations, a tensor of size\n",
    "        [batch_size, `num_classes`]\n",
    "      end_points: a dictionary from components of the network to the corresponding\n",
    "        activation.\n",
    "    \"\"\"\n",
    "    growth = 24\n",
    "    compression_rate = 0.5\n",
    "\n",
    "    def reduce_dim(input_feature):\n",
    "        return int(int(input_feature.shape[-1]) * compression_rate)\n",
    "\n",
    "    end_points = {}\n",
    "\n",
    "    with tf.variable_scope(scope, 'DenseNet', [images, num_classes]):\n",
    "        with slim.arg_scope(bn_drp_scope(is_training=is_training,\n",
    "                                         keep_prob=dropout_keep_prob)) as ssc:\n",
    "            pass\n",
    "            ##########################\n",
    "            # Put your code here.\n",
    "            \n",
    "            with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride = 1, padding = \"SAME\"):\n",
    "                             \n",
    "                def transition_layer(net, out_nums, scope = \"transition_layer\"):\n",
    "                    net = slim.conv2d(net, out_nums, [1,1], scope = scope + \"_Conv2d_1x1\")\n",
    "                    net = slim.avg_pool2d(net, [2,2], stride = 2, scope = scope + \"_AvgPool_3x3\")\n",
    "                    return net\n",
    "                \n",
    "                end_point = \"Pre_block_layer\"\n",
    "                #224 x 224 x3\n",
    "                net = slim.conv2d(images, 2*growth, [7,7], stride = 2, scope = end_point + \"_Conv2d_7x7\")\n",
    "                net = slim.max_pool2d(net, [3,3], stride =2, scope = end_point + \"_Maxpool_3x3\")\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                #56 x 56 x 48 \n",
    "                end_point = \"Block_1\"\n",
    "                net = block(net, 6, growth, scope = end_point) #56 x 56 x 8*growth\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                \n",
    "                #56 x 56 x 192\n",
    "                end_point = \"Transition_1\"\n",
    "                net = transition_layer(net, reduce_dim(net), scope = end_point)\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                #28 x 28 x 96\n",
    "                end_point = \"Block_2\"\n",
    "                net = block(net, 12, growth, scope = end_point) #28 x 28 x 16*growth\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                #28 x 28 x 384\n",
    "                end_point = \"Transition_2\"\n",
    "                net = transition_layer(net, reduce_dim(net), scope = end_point)\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                #14 x 14 x 192\n",
    "                end_point = \"Block_3\"\n",
    "                net = block(net, 32, growth, scope = end_point) #14 x 14 x 40*growth\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                #14 x 14 x 960\n",
    "                end_point = \"Transition_3\"\n",
    "                net = transition_layer(net, reduce_dim(net), scope = end_point)\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                #7 x 7 x 480\n",
    "                end_point = \"Block_4\"\n",
    "                net = block(net, 32, growth, scope = end_point) #14 x 14 x 32*growth #7 x 7 x 52*growth\n",
    "                end_points[end_point] = net\n",
    "                \n",
    "                #7 x 7 x 1248                \n",
    "                net = slim.avg_pool2d(net, [7,7], padding = \"VALID\", scope = \"Pre_logits\")\n",
    "                with slim.arg_scope(densenet_arg_scope()):                    \n",
    "                    logits = slim.conv2d(net, num_classes, [1,1])\n",
    "                    logits = tf.squeeze(logits, [1,2], scope = \"Logits\")\n",
    "                end_points[\"Logits\"] = logits\n",
    "                end_points[\"Predictions\"] = slim.softmax(logits, scope = \"Predictions\")\n",
    "                \n",
    "                \n",
    "        ##########################\n",
    "\n",
    "    return logits, end_points\n",
    "\n",
    "\n",
    "def bn_drp_scope(is_training=True, keep_prob=0.8):\n",
    "    keep_prob = keep_prob if is_training else 1\n",
    "    with slim.arg_scope(\n",
    "        [slim.batch_norm],\n",
    "            scale=True, is_training=is_training, updates_collections=None):\n",
    "        with slim.arg_scope(\n",
    "            [slim.dropout],\n",
    "                is_training=is_training, keep_prob=keep_prob) as bsc:\n",
    "            return bsc\n",
    "\n",
    "\n",
    "def densenet_arg_scope(weight_decay=0.004):\n",
    "    \"\"\"Defines the default densenet argument scope.\n",
    "\n",
    "    Args:\n",
    "      weight_decay: The weight decay to use for regularizing the model.\n",
    "\n",
    "    Returns:\n",
    "      An `arg_scope` to use for the inception v3 model.\n",
    "    \"\"\"\n",
    "    with slim.arg_scope(\n",
    "        [slim.conv2d],\n",
    "        weights_initializer=tf.contrib.layers.variance_scaling_initializer(\n",
    "            factor=2.0, mode='FAN_IN', uniform=False),\n",
    "        activation_fn=None, biases_initializer=None, padding='SAME',\n",
    "            stride=1) as sc:\n",
    "        return sc\n",
    "\n",
    "\n",
    "densenet.default_image_size = 224\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
